<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" @reset="clearSearch">
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')" prop="loanRecordId">
          <el-input v-model="page.loanRecordId"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="name">
          <el-input v-model="page.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证号码')" label-width="100px" prop="phone">
          <el-input v-model="page.idCard"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('黑猫分')" prop="score">
          <el-row :gutter="24" style="margin: 0">
            <el-col :span="11" style="padding: 0">
              <el-input v-model="page.scoreStart" oninput="value = value.replace(/[^\d]/g, '')"/>
            </el-col>
            <el-col class="line" style="padding: 0;text-align: center;line-height: 32px" :span="2">-</el-col>
            <el-col :span="11" style="padding: 0">
              <el-input v-model="page.scoreEnd" oninput="value = value.replace(/[^\d]/g, '')"/>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[531]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select v-model="page.productName" style="width: 100%" clearable>
            <el-option v-for="item in productList" :label="item.appName" :key="item.productId"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户状态')" prop="isRepeatedBorrowing">
          <el-select style="width: 100%" v-model="page.isRepeatedBorrowing" clearable>
            <el-option :label="$t('复借')" :value="1"></el-option>
            <el-option :label="$t('初借')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('白名单')" prop="isWhite">
          <el-select style="width: 100%" v-model="page.isWhite" clearable>
            <el-option :label="$t('是')" :value="1"></el-option>
            <el-option :label="$t('否')" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('机审状态')" prop="machine">
          <el-select style="width: 100%" v-model="page.machine" clearable>
            <el-option :label="$t('通过')" :value="0"></el-option>
            <el-option :label="$t('拒绝')" :value="1"></el-option>
            <el-option :label="$t('审核中')" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('申请时间')" prop="applyTimeValue">
          <el-date-picker
              v-model="page.applyTimeValue"
              style="width: 100%"
              type="daterange"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>

    <el-card style="margin-top: 10px" shadow="never">
      <el-row style="margin: 10px 0;text-align: right">
        <el-popconfirm
            :title="$t('是否批量通过?')"
            @onConfirm="batchPass"
        >
          <el-button slot="reference" style="margin-right: 10px" type="primary" v-show="$permiss[559]"
          >{{ $t('批量通过') }}
          </el-button>
        </el-popconfirm>
        <el-popconfirm
            :title="$t('是否批量拒绝?')"
            @onConfirm="batchRefuse"
        >
          <el-button slot="reference" type="primary" v-show="$permiss[558]">{{ $t('批量拒绝') }}</el-button>
        </el-popconfirm>
      </el-row>
      <el-row>
        <Table :table-column="tableColumn" :table-data="tableData" row-key="id" :page="page"
               @handleSizeChange="handleSizeChange"
               :loading="loading"
               @handleCurrentChange="handleCurrentChange" @handleSelectionChange="handleSelectionChange">
          <template slot="first">
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column :label="this.$t('订单编号')" prop="loanRecordId" align="center" width="200">
              <template slot-scope="scope">
                <el-link v-if="$permiss[64]" type="primary" :underline="false" @click="goOrderDetails(scope.row)">{{
                    scope.row.loanRecordId
                  }}
                </el-link>
                <span v-else>{{ scope.row.loanRecordId }}</span>
              </template>
            </el-table-column>

          </template>
          <template slot="phone" slot-scope="{row}">
            <el-popover
                v-if="$permiss[1319]"
                placement="right"
                width="120px"
                trigger="click">
              <SelectCallPhone :phone="callPhoneNumber" :modeType="0" :userId="row.userId" :orderId="row.loanRecordId"/>
              <el-link slot="reference" @click="callPhone(row)" :underline="false" type="primary">{{
                  row.phone
                }}
              </el-link>
            </el-popover>
            <div v-else>{{ row.phone }}</div>
          </template>
        </Table>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import {fetchBackOrderList, batchPass, batchRefuse} from "@/api/order";
import {dateFormatSection} from "@/utils/tools";
import {selectProduct} from "@/api/system";
import {getUserPhone} from '@/api/user'
import EventBus from '@/utils/eventBus'
import eventBus from "@/utils/eventBus";
import {encrypt} from "@/utils/encrypt";

export default {
  name: 'orderAgency',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      userStatusList: [],
      productList: [],
      tableColumn: [
        {label: this.$t('用户姓名'), prop: 'name', align: 'center'},
        {label: this.$t('手机号码'), prop: 'phone', align: 'center', slot: 'phone', minWidth: 150},
        {label: this.$t('身份证号码'), prop: 'idcard', align: 'center', minWidth: 100},
        {label: this.$t('白名单'), prop: 'isWhite', align: 'center'},
        {label: this.$t('申请时间'), prop: 'loanTime', align: 'center', width: 150},
        {label: this.$t('申请金额'), prop: 'loanAmount', align: 'center'},
        {label: this.$t('借款周期'), prop: 'loanTerm', align: 'center'},
        {label: this.$t('黑猫分'), prop: 'score', align: 'center', width: 100},
        {label: this.$t('机审状态'), prop: 'machine', align: 'center', isHtml: true},
        {label: this.$t('APP名称'), prop: 'appName', align: 'center'},
      ],
      tableData: [],
      selectRows: [],
      loading: false,
      callPhoneNumber: null
    }
  },
  mounted() {
    this.getTableData()
    this.getAppList()
    // 监听审核成功事件
    eventBus.$on('examineSuccess', this.getTableData)
  },
  methods: {
    async getAppList() {
      this.productList = await selectProduct().then(res => res.data)
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectRows = val
    },
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.getTableData()
    },
    async getTableData() {
      const [datetimeStart, datetimeEnd] = dateFormatSection(this.page.applyTimeValue)
      const params = {
        datetimeStart, datetimeEnd,
        ...this.page
      }
      // 删除日期属性
      delete params.applyTimeValue
      this.loading = true
      const res = await fetchBackOrderList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        const machineStatus = (value, color) => {
          return `<span class="highlight" style="color: ${color}">${value}</span>`
        }
        this.tableData = list.map(item => {
          item.machine = item.machine === 0 ? machineStatus(this.$t('通过'), '#4ce308') : item.machine === 1 ? machineStatus(this.$t('拒绝'), '#f51458') : machineStatus(this.$t('审核中'))
          item.auditStatus === 0 ? this.$t('未审核') : item.auditStatus === 1 ? this.$t('拒绝') : this.$t('通过')
          item.upApprovalResult = item.upApprovalResult === 2 ? this.$t('通过') : ''
          item.isWhite = item.isWhite === 1 ? this.$t('是') : item.isWhite === 2 ? this.$t('否') : ''
          return item
        })
        this.page = Object.assign({}, this.page, {
          total: total
        })
        this.loading = false
      }
    },
    // 批量同意
    async batchPass() {
      if (this.selectRows.length === 0) return this.$message.error(this.$t('请先选择订单'))
      const selectRows = this.selectRows.map(item => item.approvalId)
      const res = await batchPass(selectRows)
      if (res.code === 1) {
        this.selectRows = []
        this.$message.success(this.$t('操作成功'))
        this.getTableData()
      }
    },
    // 打电话
    async callPhone({userStubId}) {
      const res = await getUserPhone({userStubId: userStubId})
      if (res.code === 1) {
        this.callPhoneNumber = res.data.phone
      }
    },
    // 批量拒绝
    async batchRefuse() {
      if (this.selectRows.length === 0) return this.$message.error(this.$t('请先选择订单'))
      const selectRows = this.selectRows.map(item => item.approvalId)
      const res = await batchRefuse(selectRows)
      if (res.code === 1) {
        this.selectRows = []
        this.$message.success(this.$t('操作成功'))
        this.getTableData()
      }
    },
    goOrderDetails(row) {
      /*
      * loanAmount 申请金额
      * */
      const query = {
        userStubId: row.userStubId,
        userId: row.userId,
        approvalId: row.approvalId,
        orderId: row.loanRecordId,
        loanAmount: row.loanAmount,
        permissId: 64
      }
      this.$router.push({
        path: '/order/orderDetails',
        query: {
          params: encrypt(query)
        }
      })
    }
  },
  beforeDestroy() {
    eventBus.$off('examineSuccess', this.getTableData)
  }
}
</script>

<style scoped>

</style>
